← Back

ASYNCHRONICITY IN JAVASCRIPT

Asynchronicity lets JavaScript start a slow operation and continue doing other work while waiting for the result.

This note explains asynchronicity in simple language.

You will learn:

  1. what synchronous code is
  2. what asynchronous code is
  3. why asynchronous operations are needed
  4. why this is not the same as multithreading
  5. how setTimeout() works
  6. how clearTimeout() works
  7. how setInterval() works
  8. how clearInterval() works
  9. what timer IDs are
  10. important timer details and beginner mistakes

1. What is synchronous code?

Synchronous code runs step by step.

This means the next instruction cannot start until the current instruction finishes. The processor works on one instruction, then moves to the next one, then to the next one.

Example

console.log("First log");
console.log("Second log");
console.log("Third log");

Output

First log
Second log
Third log

The order in the console is exactly the same as the order in the code, because everything runs one after another.

Diagram 1. Synchronous execution

Step 1 -> Step 2 -> Step 3 -> Step 4

In synchronous code, each next step waits for the previous one to finish first. There is no jumping ahead.

2. Why synchronous code can be a problem

Some operations are fast, for example:

But some operations are slow, for example:

If these slow operations were handled in a blocking way, the processor would simply sit and wait instead of doing other useful work. That would make the program freeze.

Diagram 2. Problem with blocking code

Start request
-> wait...
-> wait...
-> wait...
-> continue program

During the waiting time, other code cannot continue. That is why blocking behavior is bad for user interfaces.

3. Real-life analogy: ticket queue

Synchronous work is like standing in a train ticket line.

You cannot buy your ticket until the person in front of you finishes. The person behind you cannot start until you finish. Everyone must wait in strict order.

Diagram 3. Ticket queue

Person 1 finishes
-> Person 2 finishes
-> Person 3 finishes
-> Person 4 finishes

Only one person is served at a time, and everyone else waits. This is how synchronous execution feels.

4. What is asynchronous code?

Asynchronous code lets the program start a slow operation and then continue doing other work while waiting for the result.

When the slow operation is finished, JavaScript is notified and can process the result.

This is very useful for:

Diagram 4. Asynchronous execution

Start slow operation
-> do other work
-> do other work
-> slow operation finishes
-> process result

The important idea is this: starting the operation and processing its result are two different moments.

5. Real-life analogy: restaurant

Asynchronous work is like ordering food in a restaurant.

You place your order, then you do not block the whole restaurant while your food is being prepared. Other people can also order. When your food is ready, you receive it.

Diagram 5. Restaurant analogy

Order food
-> kitchen prepares it
-> you do other things meanwhile
-> food is ready
-> you receive it

You do not stand frozen during the cooking time. That is the main idea of asynchronous behavior.

6. Why asynchronous code is useful in interfaces

Imagine the user sends a comment to the server, and at the same time wants to open a sidebar with fresh news.

If the comment request blocked the whole interface, the page would freeze until the server responded. That would feel slow and uncomfortable.

With asynchronous code, the request runs in the background, and the user can still interact with the page immediately.

Diagram 6. Interface without async vs with async

Without async:
submit comment
-> interface freezes
-> wait for server
-> interface works again

With async:
submit comment
-> request runs in background
-> user opens sidebar immediately

This is why asynchronous code is so important in modern web development.

7. JavaScript is still single-threaded

A very important point: JavaScript is single-threaded.

That means at one exact moment, only one operation is executed.

So asynchronous programming does not mean JavaScript is suddenly doing many things at the exact same time on one thread.

Instead, it means some operations are started, postponed, and handled later when their result is ready.

Diagram 7. Single-threaded but asynchronous

One thread
-> one operation at a time
-> but some operations can be scheduled for later

This is one of the most important beginner ideas: asynchronous code is about delayed handling, not about many JavaScript instructions running truly in parallel on the same thread.

8. Asynchronicity is not multithreading

Do not confuse asynchronicity with multithreading.

They are different ideas.

Think about a kitchen:

Diagram 8. Async vs multithreading

Synchronous:
task A -> task B -> task C

Asynchronous:
start A
start B
do C while waiting
finish A/B later

Multithreaded:
worker 1 does A
worker 2 does B
both run in parallel

Asynchronous JavaScript usually means smart scheduling on one thread, not true parallel thread execution.

9. setTimeout()

setTimeout() lets you schedule a one-time function call after a certain delay.

The timers are provided by the browser, not by the core JavaScript language itself, and they are available on the global window object.

Syntax

const timerId = setTimeout(callback, delay, arg1, arg2, ...);

Where:

Diagram 9. setTimeout() structure

setTimeout(callback, delay)
-> register delayed function call
-> browser waits for delay
-> callback runs once

setTimeout() does not immediately run the callback. It only schedules it for later.

10. setTimeout() example

console.log("First log");

setTimeout(() => {
  console.log("Second log");
}, 2000);

console.log("Third log");

Output

First log
Third log
Second log

The order is different from the code order because the callback inside setTimeout() is delayed for 2 seconds.

Diagram 10. Execution order with setTimeout()

1. "First log"
2. register timeout
3. "Third log"
4. after 2 seconds -> "Second log"

The setTimeout() call itself runs synchronously, but the callback it registers runs asynchronously later.

11. What does setTimeout() return?

setTimeout() returns a numeric timer identifier.

Example

const timerId = setTimeout(() => {
  console.log("Hello!");
}, 3000);

console.log(timerId);

This numeric ID can later be used to cancel that timeout.

Diagram 11. Timer ID

setTimeout(...)
-> creates timer
-> returns numeric ID
-> ID can be used later

The timer ID is like the name or number of that specific scheduled timeout.

12. clearTimeout()

If you want to cancel a timeout before it runs, use:

clearTimeout(id);

You must pass the timer ID returned by setTimeout().

Example

const greet = () => {
  console.log("Hello!");
};

const timerId = setTimeout(greet, 3000);

clearTimeout(timerId);

Because the timeout is cancelled before 3 seconds pass, nothing is printed.

Diagram 12. Cancelling a timeout

setTimeout(...)
-> timer created
-> clearTimeout(timerId)
-> timer removed
-> callback never runs

If the timeout is cleared in time, the scheduled function call will never happen.

13. Common beginner mistake with clearTimeout()

You do not pass:

You pass only:

Diagram 13. What goes into clearTimeout()

Wrong:
clearTimeout(callback)
clearTimeout(delay)

Correct:
clearTimeout(timerId)

Always save the timer ID if you may need to cancel the timeout later.

14. setInterval()

setInterval() is similar to setTimeout(), but instead of running once, it repeats the callback over and over after the given delay.

Syntax

const intervalId = setInterval(callback, delay, arg1, arg2, ...);

It also returns a numeric identifier.

Diagram 14. setInterval() structure

setInterval(callback, delay)
-> wait delay
-> run callback
-> wait delay
-> run callback again
-> repeat

This is for repeated actions, not one-time delayed actions.

15. Example of setInterval()

const greet = () => {
  console.log("Hello!");
};

const intervalId = setInterval(greet, 3000);

This means greet will be called every 3 seconds until the interval is cancelled.

Diagram 15. Interval repetition

3 sec -> callback
3 sec -> callback
3 sec -> callback
3 sec -> callback
...

An interval keeps repeating until you stop it manually.

16. What does setInterval() return?

Just like setTimeout(), setInterval() returns a numeric interval ID.

That ID is later used to stop the interval.

Diagram 16. Interval ID

setInterval(...)
-> creates repeating timer
-> returns numeric ID

This ID is needed for clearInterval().

17. clearInterval()

To stop an interval, use:

clearInterval(id);

You must pass the interval ID returned by setInterval().

Example

const greet = () => {
  console.log("Hello!");
};

const intervalId = setInterval(greet, 3000);

clearInterval(intervalId);

Because the interval is cleared before it gets a chance to run, nothing is printed.

Diagram 17. Cancelling an interval

setInterval(...)
-> interval created
-> clearInterval(intervalId)
-> repeated calls are cancelled

Without clearInterval(), the callback would continue repeating.

18. Common beginner mistake with clearInterval()

You do not pass:

You pass only:

Diagram 18. What goes into clearInterval()

Wrong:
clearInterval(callback)
clearInterval(delay)

Correct:
clearInterval(intervalId)

This works the same way as timeout cancellation.

19. Minimum timer delay

Browsers have a minimum possible timer delay, approximately from 0 to 4 milliseconds.

According to the standard, the minimum delay is 4 milliseconds, so in practice setInterval(cb, 1) and setInterval(cb, 4) behave the same.

Diagram 19. Minimum delay idea

Requested delay too small
-> browser still uses minimum practical delay

So very tiny delay values do not make timers infinitely fast.

20. Timers are not perfectly exact

A timer may run less often than the delay says.

This can happen because:

Browsers keep running timeouts and intervals even in inactive tabs, but the frequency becomes lower.

Diagram 20. Timer accuracy

Timer scheduled
-> browser tries to run it on time
-> heavy load or inactive tab
-> actual run may be later

Timers are scheduled tools, not perfect stopwatch tools.

21. Easy memory rules

Synchronous = one step waits for previous step
Asynchronous = start now, handle result later

setTimeout() = run once later
clearTimeout() = cancel timeout

setInterval() = run again and again
clearInterval() = stop interval

Both setTimeout() and setInterval()
-> return numeric IDs

22. Quick summary

23. Final conclusion

If you understand these ideas:

synchronous code
asynchronous code
single-threaded JavaScript
setTimeout()
clearTimeout()
setInterval()
clearInterval()
timer IDs

then you already have a strong foundation for asynchronous behavior in JavaScript.

This topic is very important because real web applications constantly use delayed actions, repeated actions, background waiting, and non-blocking behavior.

← Back